﻿using System;
using System.Collections.Generic;
using TheOutfield.UmbExt.UniversalMediaPicker.Interfaces;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using umbraco.BusinessLogic.Utils;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerDataType : BaseDataType, IDataType
    {
        private static readonly object Locker = new object();

        private IData data;
        private IDataEditor dataEditor;
        private IDataPrevalue dataPrevalueEditor;

        public override Guid Id
        {
            get { return new Guid("CB4BD24C-C807-11DF-ADE9-B87EDFD72085"); }
        }

        public override string DataTypeName
        {
            get { return "UniversalMediaPicker"; }
        }

        public override IData Data
        {
            get 
            {
                if (data == null)
                    data = new UniversalMediaPickerData(this);

                return data;
            }
        }

        public override IDataEditor DataEditor
        {
            get
            {
                if (dataEditor == null)
                    dataEditor = new UniversalMediaPickerDataEditor(this);

                return dataEditor;
            }
        }

        public override IDataPrevalue PrevalueEditor
        {
            get
            {
                if (dataPrevalueEditor == null)
                     dataPrevalueEditor = new UniversalMediaPickerPrevalueEditor(this);

                return dataPrevalueEditor;
            }
        }

        public UniversalMediaPickerConfig Config
        {
            get
            {
                var prevalues = PreValues.GetPreValues(DataTypeDefinitionId);
                if (prevalues.Count > 0)
                {
                    var prevalue = (PreValue)prevalues[0];
                    return prevalue.Value.DeserializeJsonTo<UniversalMediaPickerConfig>();
                }

                return new UniversalMediaPickerConfig();
            }

            set
            {
                var json = value.SerializeToJson();

                lock (Locker)
                {
                    var prevalues = PreValues.GetPreValues(DataTypeDefinitionId);
                    if (prevalues.Count > 0)
                    {
                        var prevalue = (PreValue)prevalues[0];
                        prevalue.Value = json;
                        prevalue.Save();
                    }
                    else
                    {
                        var prevalue = PreValue.MakeNew(DataTypeDefinitionId, json);
                        prevalue.Save();
                    }
                }
            }
        }

        
    }
}